<body>
    <canvas id='cvs' width='600' height='600'>
        您的浏览器不支持
    </canvas>

    <script>
        var cvs = document.querySelector('#cvs');
        var ctx = cvs.getContext('2d');

        function Ball(cvs, x, y, r, color) {
            this.cvs = document.querySelector('#' + cvs);
            this.ctx = this.cvs.getContext('2d');
            this.x = x;
            this.y = y;
            this.r = r;
            this.color = color;

            this.stepX = Math.random() * 10 + 1;
            this.stepY = Math.random() * 10 + 1;
            this.init();
        }

        Ball.prototype = {
            init: function () {
                this.drawBall();
            },
            drawBall: function () {
                this.ctx.beginPath();
                this.ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
                this.ctx.fillStyle = this.color;
                this.ctx.fill();
                this.ctx.closePath();
            },
            move: function () {
                //这样判断有一次是不准的,当小球还差一次贴边时,这时x+r已经>width了,等于是少走了一步就直接反弹了.
                //贴右边反弹
                if (this.x + this.r > this.cvs.width) {
                    this.stepX = -Math.abs(this.stepX);
                }
                //贴左边反弹
                if (this.x - this.r < 0) {
                    this.stepX = Math.abs(this.stepX);
                }
                //贴下边反弹
                if (this.y + this.r > this.cvs.height) {
                    this.stepY = -Math.abs(this.stepY);
                }
                //贴上边反弹
                if (this.y - this.r < 0) {
                    this.stepY = Math.abs(this.stepY);
                }

                this.x += this.stepX;
                this.y += this.stepY;
                this.drawBall();
            },
        }

        var balls = [];
        for (var i = 0; i < 10; i++) {
            var num = Math.random() * (70 - 20 + 1) + 20;
            var color1 = Math.floor(Math.random() * 256);
            var color2 = Math.floor(Math.random() * 256);
            var color3 = Math.floor(Math.random() * 256);
            balls.push(new Ball('cvs', num, num, num, 'rgb(' + color1 + ',' + color2 + ',' + color3 + ')'));
        }
        setInterval(function () {
            //每隔17ms,所有的小球统一清一次画布,而不是在move函数中,每个小球每隔17ms清一次画布.
            ctx.clearRect(0, 0, cvs.width, cvs.height);
            for (var i = 0; i < balls.length; i++) {
                balls[i].move();
            }
        }, 17)

    </script>
</body>